package pr.lanmu.config.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import pr.lanmu.common.mapper.UserMapper;
import pr.lanmu.common.po.User;
import pr.lanmu.config.base.UserBase;
import pr.lanmu.config.constant.Code;

/**
 * 凭证生成和解密工具类
 */
@Component
public class JwtUtil {
    @Value("${jwt-salt-secret}")
    private String saltSecret;
    @Autowired
    private UserMapper userMapper;

    /**
     * 创建3天有效的jwt
     *
     * @param id .
     * @return .
     */
    public String createJwtStr(Long id) {
        return JWT.create()
                .withClaim("id", id)
                .sign(Algorithm.HMAC256(saltSecret));
    }

    /**
     * 解析jwt
     *
     * @param jwtJson .
     * @return .
     */
    public UserBase verifierJwtInfo(String jwtJson) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(saltSecret))
                .build();
        DecodedJWT decodedJWT;
        try {
            decodedJWT = jwtVerifier.verify(jwtJson);
        } catch (TokenExpiredException e) {
            Log.warn(Code.JWT_TOKEN_EXPIRED.getDescribe());
            throw Code.getException(Code.JWT_TOKEN_EXPIRED);
        } catch (Exception e) {
            Log.warn(Code.JWT_TOKEN_EXCEPTION.getDescribe());
            throw Code.getException(Code.JWT_TOKEN_EXCEPTION);
        }
        Long id = decodedJWT.getClaim("id")
                .asLong();
        User user = userMapper.selectOneById(id);
        UserBase userBase = ConvertUtil.copy(user, new UserBase());
        userBase.setPassword(null);
        return userBase;
    }
}
